package edu.service.impl;

import edu.repository.UserRoleRepository;
import edu.service.UserService;
import edu.vo.Role;
import edu.vo.User;
import edu.repository.UserRepository;
import edu.vo.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public Optional<User> getUserById(Integer id) {
        return userRepository.findById(id);
    }

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public Page<User> getAllUsers(Pageable pageable) {
        // 直接从仓库获取分页数据
        Page<User> userPage = userRepository.findAll(pageable);

        // 处理用户角色信息
        userPage.getContent().forEach(user -> {
            // 获取用户角色
            List<UserRole> userRoles = userRoleRepository.getAllByUser(user);
            user.setUserRoles(userRoles);
        });

        return userPage;
    }

    @Override
    public void deleteUserById(Integer id) {
        userRepository.deleteById(id);
    }

    @Override
    public User updateUser(Integer id, User user) {
        return userRepository.findById(id)
                .map(existingUser -> {
                    existingUser.setUserName(user.getUserName());
                    existingUser.setPassword(user.getPassword());
                    existingUser.setSalt(user.getSalt());
                    existingUser.setLocked(user.getLocked());
                    existingUser.setCreatedAt(user.getCreatedAt());
                    return userRepository.save(existingUser);
                })
                .orElse(null);
    }

    @Override
    public Optional<User> findByUserName(String userName) {
        return userRepository.findByUserName(userName);
    }
}